package com.example.redismanual.dao.actionExamples.BitmapExamples;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class ActionRecorder {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    private String getActionKey(String action){
        return "ActionRecorder::" + action;
    }

    public void action_performBy_user(String action,String userId){
        String key = getActionKey(action);
        redisTemplate.opsForValue().setBit(key, Long.parseLong(userId),true);
    }

    public Boolean action_isPerformedBy_user(String action,String userId){
        String key = getActionKey(action);
//        return redisTemplate.opsForValue().getBit(key, Long.parseLong(userId));
        return redisTemplate.execute((RedisCallback<Boolean>) con-> con.getBit(key.getBytes(StandardCharsets.UTF_8), Long.parseLong(userId)));
    }


    public Long count_performed(String action){
        String key = getActionKey(action);
        return redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(key.getBytes()));
    }
}
